#include "my_http.h"

//my_http::my_http(QObject *parent) : QObject(parent)
//{

//}
My_Http::My_Http()
{

    // 初始化 QNetworkAccessManager
    get_AccessToken_network = new QNetworkAccessManager();
    get_Plate_number_network = new QNetworkAccessManager();

    // 设置 client_id 和 client_secret
    client_id = "yl7H1PFDJEq39A8J1VPlm9bK";
    client_secret = "AJQzKAGG4910TTayu5UV9OYa9bGqQ50E";
    grant_type = "client_credentials";

    // 设置鉴权 url
    Access_url =
            QString("https://aip.baidubce.com/oauth/2.0/token?grant_type=%1&client_id=%2&client_secret=%3")
            .arg(grant_type)
            .arg(client_id)
            .arg(client_secret);

    // 连接 finished 信号到 onTokenReceived 槽函数
    connect(get_AccessToken_network, &QNetworkAccessManager::finished, this, &My_Http::onTokenReceived);
    connect(get_Plate_number_network, &QNetworkAccessManager::finished, this, &My_Http::onPlateReceived);

}

void My_Http::get_AccessToken()
{
    QNetworkRequest request(Access_url);

    // 设置请求头
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setRawHeader("Accept", "application/json");

    // 发送
    QByteArray postData = "";  // 可以根据需求设置数据
    get_AccessToken_network->post(request , postData);

    // 事件循环机制
    QEventLoop eventLoop;
    connect(get_AccessToken_network, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

}

void My_Http::get_plate_number(QByteArray img_Base64)
{
    // 设置识别ur
    plate_num_url =
            QString("https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=%1")
            .arg(Access_token);

    // 创建POST请求
    QNetworkRequest request(plate_num_url);

    // 设置请求头
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");

    // 编码图片数据并发送请求
    QByteArray postData;
    postData.append("image=" + QUrl::toPercentEncoding(img_Base64));

    // 发送请求进行车牌识别
    get_Plate_number_network->post(request, postData);

    // 事件循环机制
    QEventLoop eventLoop;
    connect(get_Plate_number_network, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
}

QString My_Http::get_data()
{
    QString data = "颜色: ";
    data += this->plate_col;
    data += " 车牌: ";
    data += this->plate_num;
    return  data;
}



void My_Http::onTokenReceived(QNetworkReply *reply)
{
    qDebug() << "运行槽函数";

    // 判断是否有错误
    if(reply->error() == QNetworkReply::NoError)
    {
        // 读取响应结果
        QByteArray response = reply->readAll();
        // qDebug() << "响应数据:" << response;

        // 将 QByteArray 转换为 QJsonDocument
        QJsonDocument jsonDoc = QJsonDocument::fromJson(response);

        // 确保 JSON 是一个对象
        if (jsonDoc.isObject()) {
            QJsonObject jsonObj = jsonDoc.object();

            // 提取 access_token
            Access_token = jsonObj["access_token"].toString();
            qDebug() << "Access Token:" << Access_token;

            // 你可以在这里存储 access_token 或执行其他操作
        } else {
            qDebug() << "Invalid JSON format!";
        }
    }
    else
    {
        qDebug() << "请求错误:" << reply->errorString();
    }

    // 删除 reply 对象，释放资源
    reply->deleteLater();
}

void My_Http::onPlateReceived(QNetworkReply *reply)
{
    qDebug() << "处理车牌识别结果";

    // 判断是否有错误
    if(reply->error() == QNetworkReply::NoError)
    {
        // 读取响应结果
        QByteArray response = reply->readAll();
        qDebug() << response;

        // 解析 JSON 数据
        QJsonDocument doc = QJsonDocument::fromJson(response);

        // 判断是否成功解析
        if (doc.isNull()) {
            qDebug() << "无效的 JSON 数据";
            return;
        }

        // 获取根对象
        QJsonObject rootObj = doc.object();

        // 解析 "words_result" 对象
        QJsonObject wordsResultObj = rootObj.value("words_result").toObject();
        QString number = wordsResultObj.value("number").toString();
        QString color = wordsResultObj.value("color").toString();

        this->plate_col = color;
        this->plate_num = number;

        // 输出车牌号和颜色
        qDebug() << "车牌号：" << number;
        qDebug() << "颜色：" << color;
    }
    else
    {
        qDebug() << "请求错误:" << reply->errorString();
    }

    // 删除 reply 对象，释放资源
    reply->deleteLater();
}

